import urllib.parse
import urllib.request


# http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
}
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'

# 获取城市
def getSearchParams(page,city):
    data = {
        'cname': city,
        'pageIndex': page,
        'pageSize': '10'
    }
    searchParams = urllib.parse.urlencode(data).encode("utf-8")
    return searchParams

# 获取json数据
def getContext(searchParams):
    reqObj = urllib.request.Request(url=url, headers=headers, data=searchParams)
    resp = urllib.request.urlopen(reqObj)
    context = resp.read().decode('utf-8')
    return context


def download(city,index,context):
    with open("肯德基门店信息_" + city + "_" + str(index)+'.json', 'w', encoding='utf-8') as fp:
        fp.write(context)


if __name__ == '__main__':
    page = int(input("爬取第几页？"))
    city = input("什么城市？")
    for index in range(1,page+1):
        searchParams = getSearchParams(index,city)
        context = getContext(searchParams)
        if context != '[]':
            download(city,index,context)
